<?php

namespace Lib\Util;

class Comm extends \Home {

    public static $pattern = '/^[\w\.-]+(\.\w+)*@(\w)+((\.\w+)+)$/';

    public static function getUrlPath($route = null) {
        $uri = self::getUri();
        $result = array();
        $result['match'] = array();
        if ($route && is_array($route)) {
            foreach ($route as $k => $v) {
                $match = array();
                if (preg_match($k, $uri, $match)) {
                    if (is_array($v)) {
                        $myUri = array_shift($v);
                    } else {
                        $myUri = $v;
                    }
                    $uri = trim($myUri, '/');
                    array_shift($match);
                    if ($v && is_array($v)) {
                        $match = array_merge($match, $v);
                    }
                    $result['match'] = $match;
                    break;
                }
            }
        }
        $path = explode('/', $uri);
        $path = array_filter($path);
        $result['path'] = $path;
        return $result;
    }

    public static function checkEmailFormat($email) {
        return preg_match(self::$pattern, $email);
    }

    public static function checkPhoneNumberFormat($phone) {
        return preg_match('/^((\+86)|(86))?\d{11}$/', $phone);
    }

    public static function getUri() {
        $uri = $_SERVER['REQUEST_URI'];
        $arr = explode('?', $uri);
        $uri = array_shift($arr);
        $uri = trim($uri, '/');
        return $uri;
    }

    public static function rMkdir($path) {
        $path = $path . '/1';
        $arr = self::getDirTree($path);
        $arr = array_reverse($arr);
        foreach ($arr as $dir) {
            if (!file_exists($dir)) {
                mkdir($dir);
            }
        }
    }

    public static function unescape($str) {
        $ret = '';
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            if (($str[$i] == '%' || $str[$i] == '\\') && $str [$i + 1] == 'u') {
                $val = hexdec(substr($str, $i + 2, 4));
                if ($val < 0x7f)
                    $ret .= chr($val); else if ($val < 0x800)
                    $ret .= chr(0xc0 | ($val >> 6)) . chr(0x80 | ($val & 0x3f)); else
                    $ret .= chr(0xe0 | ($val >> 12)) . chr(0x80 | (($val >> 6) & 0x3f)) . chr(0x80 | ($val & 0x3f));
                $i += 5;
            } else if ($str [$i] == '%') {
                $ret .= urldecode(substr($str, $i, 3));
                $i += 2;
            } else
                $ret .= $str [$i];
        }

        return $ret;
    }

    public static function request($url, $postData = null, $timeout = 5, $header = array(), $curlProcess = null, $isHeader = 0) {
        $ch = curl_init($url);
        if (!$curlProcess) {
            $curlProcess = function(){};
        }
        if ($curlProcess) {
            $curlProcess($ch);
        }
        if ($postData) {
            curl_setopt($ch, CURLOPT_POST, 1);
            if (is_array($postData)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            }
        } else {
            curl_setopt($ch, CURLOPT_POST, 0);
        }
        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_HEADER, $isHeader);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($timeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        }
        $return = curl_exec($ch);
        return $return;
    }

    public static function diffNow($time)
    {
        $now = time();
        $diff = $now - $time;
        if ($diff < 60) {
            return $diff . '秒';
        } else if ($diff < 3600) {
            $m = (int)($diff / 60);
            return $m . '分钟';
        } else if ($diff < 24 * 3600) {
            $h = (int)($diff / 3600);
            return $h . '小时';
        } else {
            $d = (int)($diff / 24 / 3600);
            return $d . '天';
        }
    }

    public static function setCookie($key, $value = '', $expire = 0)
    {
        if ($value) {
            if (is_object($value) || is_array($value)) {
                $value = json_encode($value);
            } else if ($value === true) {
                $value = 1;
            } else if ($value === false) {
                $value = 0;
            }
            setcookie($key, $value, $expire, '/');
            $_COOKIE[$key] = $value;
        } else {
            setcookie($key, '', -1, '/');
            if (isset($_COOKIE[$key])) {
                unset($_COOKIE[$key]);
            }
        }
    }

    public static function redirect($url, $type = '302') {
        if ($type == 301) {
            header('HTTP/1.1 301 Moved Permanently');
        }
        header('Location:' . $url);
        \Main::sysExit();
    }

    public static function utf8_truncate($string, $len) {
        $l = mb_strlen($string);
        $str = '';
        $ll = 0;
        for ($i = 0; $i < $l; $i++) {
            $s = mb_substr($string, $i, 1);
            $ll += strlen($s);
            if ($ll > $len) {
                break;
            }
            $str .= $s;
        }
        return $str;
    }

    public static function truncate($string, $sublen = 80, $etc = '...', $break_words = false, $middle = false)
    {
        $start = 0;
        $code = "UTF-8";
        if ($code == 'UTF-8') {
            //如果有中文则减去中文的个数
            $cncount = self::cncount($string);

            if ($cncount > ($sublen / 2)) {
                $sublen = ceil($sublen / 2);
            } else {
                $sublen = $sublen - $cncount;
            }

            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            $t_string = array();
            preg_match_all($pa, $string, $t_string);

            $str = join('', array_slice($t_string[0], $start, $sublen));
            $str = rtrim($str, '.');
            if (count($t_string[0]) - $start > $sublen) {
                return $str . $etc;
            } else {
                return $str;
            }
        } else {
            $start = $start * 2;
            $sublen = $sublen * 2;
            $strlen = strlen($string);
            $tmpstr = '';

            for ($i = 0; $i < $strlen; $i++) {
                if ($i >= $start && $i < ($start + $sublen)) {
                    if (ord(substr($string, $i, 1)) > 129) {
                        $tmpstr .= substr($string, $i, 2);
                    } else {
                        $tmpstr .= substr($string, $i, 1);
                    }
                }
                if (ord(substr($string, $i, 1)) > 129) {
                    $i++;
                }
            }
            if (strlen($tmpstr) < $strlen) {
                $tmpstr .= $etc;
            }
            return $tmpstr;
        }
    }

    private static function cncount($str) {
        $len = strlen($str);
        $cncount = 0;

        for ($i = 0; $i < $len; $i++) {
            $temp_str = substr($str, $i, 1);

            if (ord($temp_str) > 127) {
                $cncount++;
            }
        }
        return ceil($cncount / 3);
    }

    /**
     * 发送post请求.
     *
     * @param string $url 请求地址.
     * @param array $postData post键值对数据.
     * @param boolean $isBuild Is user http_build_query.
     *
     * @return string
     */
    public static function sendPost($url, $postData, $isBuild = true) {
        if ($isBuild) {
            $postData = http_build_query($postData);
        }
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postData,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    public static function str2Arr($str, $code = 'utf-8') {
        $count = mb_strlen($str, $code);
        $arr = array();
        for ($i = 0; $i < $count; $i++) {
            $arr[] = mb_substr($str, $i, 1, $code);
        }
        return $arr;
    }

    public static function isChinese($str) {
        $regex = '/[\x{4e00}-\x{9fa5}]{3}/u';
        $is = preg_match($regex, $str);
        return $is;
    }

    public static function getCurrentUrl()
    {
        $host = $_SERVER['HTTP_HOST'];
        $requestUri = $_SERVER['REQUEST_URI'];
        $url = 'http://' . $host . $requestUri;
        return $url;
    }

    /**
     * 函数名称:encrypt
     * 函数作用:加密解密字符串
     * 使用方法:
     * 加密     :encrypt('str','E','nowamagic');
     * 解密     :encrypt('被加密过的字符串','D','nowamagic');
     * 参数说明:
     * $string   :需要加密解密的字符串
     * $operation:判断是加密还是解密:E:加密   D:解密
     * $key      :加密的钥匙(密匙);
     */
    public static function crypt($string, $operation, $key = '') {
        $key = md5($key);
        $key_length = strlen($key);
        $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
        $string_length = strlen($string);
        $rndkey = $box = array();
        $result = '';
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($key[$i % $key_length]);
            $box[$i] = $i;
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'D') {
            if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
                return substr($result, 8);
            } else {
                return '';
            }
        } else {
            return str_replace('=', '', base64_encode($result));
        }
    }

    public static function getUTF8Length($str, $len = 2) {
        $n = mb_strlen($str);
        $length = 0;
        for ($i = 0; $i < $n; $i++) {
            $s = mb_substr($str, 0, 1);
            if (strlen($s) > 1) {
                $length += 2;
            } else {
                $length++;
            }
        }
        return $length;
    }

	/**
	 *  获取用户所在地区，去掉市后面的。而getUA则不去掉用户的输入
	 */
	public static function getUA($ip) {
		$area = self::ip2Area($ip);
		$area_p = explode(" ", $area);
		$UA = $area_p[0];

		if ($UA == "本机地址" || $UA == '局域网') {
			$UA = '北京';
		}

		if ($UA) {
			if (strpos($UA, '市'))
				$UA = substr($UA, 0, strpos($UA, '市'));
		}

		if (strpos($UA, '市'))
			$UA = substr($UA, 0, strpos($UA, '市'));

		if (strpos($UA, '省'))
			$UA = substr($UA, 0, strpos($UA, '省'));

		return $UA;
	}

	public static function ip2Area($ip) {
		$ipDataFile = __DIR__ . '/qqwry.Dat';
		if (!$fd = @fopen($ipDataFile, 'rb')) {
			return '- Invalid IP data file';
		}

		$ip = explode('.', $ip);
		$ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];

		if (!($DataBegin = fread($fd, 4)) || !($DataEnd = fread($fd, 4)))
			return;
		@$ipbegin = implode('', unpack('L', $DataBegin));
		if ($ipbegin < 0)
			$ipbegin += pow(2, 32);
		@$ipend = implode('', unpack('L', $DataEnd));
		if ($ipend < 0)
			$ipend += pow(2, 32);
		$ipAllNum = ($ipend - $ipbegin) / 7 + 1;

		$BeginNum = $ip2num = $ip1num = 0;
		$ipAddr1 = $ipAddr2 = '';
		$EndNum = $ipAllNum;

		while ($ip1num > $ipNum || $ip2num < $ipNum) {
			$Middle = intval(($EndNum + $BeginNum) / 2);

			fseek($fd, $ipbegin + 7 * $Middle);
			$ipData1 = fread($fd, 4);
			if (strlen($ipData1) < 4) {
				fclose($fd);
				return '- System Error';
			}
			$ip1num = implode('', unpack('L', $ipData1));
			if ($ip1num < 0)
				$ip1num += pow(2, 32);

			if ($ip1num > $ipNum) {
				$EndNum = $Middle;
				continue;
			}

			$DataSeek = fread($fd, 3);
			if (strlen($DataSeek) < 3) {
				fclose($fd);
				return '- System Error';
			}
			$DataSeek = implode('', unpack('L', $DataSeek . chr(0)));
			fseek($fd, $DataSeek);
			$ipData2 = fread($fd, 4);
			if (strlen($ipData2) < 4) {
				fclose($fd);
				return '- System Error';
			}
			$ip2num = implode('', unpack('L', $ipData2));
			if ($ip2num < 0)
				$ip2num += pow(2, 32);

			if ($ip2num < $ipNum) {
				if ($Middle == $BeginNum) {
					fclose($fd);
					return '- Unknown';
				}
				$BeginNum = $Middle;
			}
		}

		$ipFlag = fread($fd, 1);
		if ($ipFlag == chr(1)) {
			$ipSeek = fread($fd, 3);
			if (strlen($ipSeek) < 3) {
				fclose($fd);
				return '- System Error';
			}
			$ipSeek = implode('', unpack('L', $ipSeek . chr(0)));
			fseek($fd, $ipSeek);
			$ipFlag = fread($fd, 1);
		}

		if ($ipFlag == chr(2)) {
			$AddrSeek = fread($fd, 3);
			if (strlen($AddrSeek) < 3) {
				fclose($fd);
				return '- System Error';
			}
			$ipFlag = fread($fd, 1);
			if ($ipFlag == chr(2)) {
				$AddrSeek2 = fread($fd, 3);
				if (strlen($AddrSeek2) < 3) {
					fclose($fd);
					return '- System Error';
				}
				$AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
				fseek($fd, $AddrSeek2);
			} else {
				fseek($fd, -1, SEEK_CUR);
			}

			while (($char = fread($fd, 1)) != chr(0))
				$ipAddr2 .= $char;

			$AddrSeek = implode('', unpack('L', $AddrSeek . chr(0)));
			fseek($fd, $AddrSeek);

			while (($char = fread($fd, 1)) != chr(0))
				$ipAddr1 .= $char;
		} else {
			fseek($fd, -1, SEEK_CUR);
			while (($char = fread($fd, 1)) != chr(0))
				$ipAddr1 .= $char;

			$ipFlag = fread($fd, 1);
			if ($ipFlag == chr(2)) {
				$AddrSeek2 = fread($fd, 3);
				if (strlen($AddrSeek2) < 3) {
					fclose($fd);
					return '- System Error';
				}
				$AddrSeek2 = implode('', unpack('L', $AddrSeek2 . chr(0)));
				fseek($fd, $AddrSeek2);
			} else {
				fseek($fd, -1, SEEK_CUR);
			}
			while (($char = fread($fd, 1)) != chr(0))
				$ipAddr2 .= $char;
		}
		fclose($fd);

		if (preg_match('/http/i', $ipAddr2)) {
			$ipAddr2 = '';
		}
		$ipaddr = "$ipAddr1 $ipAddr2";
		$ipaddr = preg_replace('/CZ88\.NET/is', '', $ipaddr);
		$ipaddr = preg_replace('/^\s*/is', '', $ipaddr);
		$ipaddr = preg_replace('/\s*$/is', '', $ipaddr);
		if (preg_match('/http/i', $ipaddr) || $ipaddr == '') {
			$ipaddr = '- Unknown';
		}

		$city = iconv('gb2312', 'UTF-8', $ipaddr);
		if ($city) {
			$tmp = explode(' ', $city);
			$city = $tmp[0];
		}
		return $city;
	}

    private static function getDirTree($dir, $dirArr = array()) {
        $path = dirname($dir);
        array_push($dirArr, $path);
        if ($path == '.' || $path == '\\' || $path == '/') {
            return $dirArr;
        }
        return self::getDirTree($path, $dirArr);
    }

}